<template>
  <div>
    <div style="width: 1400px;margin: 0px auto 0;background-color: #FFFFFF;">
      <el-form ref="bidForm" v-loading="loading" :model="bidPrice">
        <div style="padding: 0px 100px">
          <p style="margin-top: 0px;margin-bottom: 0px;font-size: 18px;text-align: center;"><span style="color: red;">竞标室-标号({{ bidPrice.sCode}})&nbsp;--&nbsp;{{ bidPrice.sName}}</span> </p>
          <el-descriptions class="bidding-hall-margin-top" size="medium" :column="3" border>
            <el-descriptions-item label-style="text-align: center;height:35px;">
              <template slot="label">
                招标公司：
              </template>
              <span style="padding-left: 15px">{{bidPrice.sUnit}}</span>
            </el-descriptions-item>
            <el-descriptions-item label-style="text-align: center;height:35px;">
              <template slot="label">
                开始时间：
              </template>
              <span style="padding-left: 15px">{{parseTime(bidPrice.uKaiTime, '{y}-{m}-{d} {h}:{i}:{s}')}}</span>
            </el-descriptions-item>
            <el-descriptions-item label-style="text-align: center;height:35px;">
              <template slot="label">
                结束时间：
              </template>
              <span style="padding-left: 15px">{{parseTime(this.uKaiEndTime, '{y}-{m}-{d} {h}:{i}:{s}')}}</span>
            </el-descriptions-item>
            <el-descriptions-item label-style="text-align: center;height:35px;">
              <template slot="label">
                招标方式：
              </template>
              <span style="padding-left: 15px" v-if="bidPrice.sWay === 1">公开招标</span>
              <span style="padding-left: 15px" v-if="bidPrice.sWay === 2">邀请招标</span>
            </el-descriptions-item>
            <el-descriptions-item label-style="text-align: center;height:35px;">
              <template slot="label">
                最小降幅：
              </template>
              <span style="padding-left: 15px">{{bidPrice.minDecline}}&nbsp;%</span>
            </el-descriptions-item>
            <el-descriptions-item label-style="text-align: center;height:35px;">
              <template slot="label">
                每次最大降幅：
              </template>
              <span style="padding-left: 15px">{{bidPrice.maxDecline}}&nbsp;%(最小降幅{{multiple}}倍)</span>
            </el-descriptions-item>
            <el-descriptions-item label-style="text-align: center;height:35px;">
              <template slot="label">
                竞标类别：
              </template>
              <span style="padding-left: 15px">{{bidPrice.biddingCategory}}</span>
            </el-descriptions-item>
            <el-descriptions-item label-style="text-align: center;height:35px;">
              <template slot="label">
                币别：
              </template>
              <span style="padding-left: 15px">{{bidPrice.currencyCategory}}</span>
            </el-descriptions-item>
            <el-descriptions-item label-style="text-align: center;height:35px;">
              <template slot="label">
                相同报价排名：
              </template>
              <span style="padding-left: 15px">{{bidPrice.sorted}}</span>
            </el-descriptions-item>
            <el-descriptions-item label-style="text-align: center;height:35px;">
              <template slot="label">
                延长时间：
              </template>
              <span style="padding-left: 15px">{{bidPrice.extendTime}}&nbsp;分钟</span>
            </el-descriptions-item>
            <el-descriptions-item label-style="text-align: center;height:35px;" span="2">
              <template slot="label">
                延时次数：
              </template>
              <span style="padding-left: 15px">{{bidPrice.extendCount}}&nbsp;次</span>
            </el-descriptions-item>
<!--            <el-descriptions-item label-style="text-align: center;height:35px;">
              <template slot="label">
                起始价：
              </template>
              <span style="padding-left: 15px">{{bidPrice.startPrice}}&nbsp;{{bidPrice.currencyCategory}}</span>
            </el-descriptions-item>-->
            <el-descriptions-item label-style="text-align: center;height:35px;" span="3">
              <template slot="label">
                竞价类别：
              </template>
              <span style="padding-left: 15px">{{bidPrice.priceCategory}}</span>
            </el-descriptions-item>
            <el-descriptions-item label-style="text-align: center;height:35px;" span="1.5">
              <template slot="label">
                小数保留位数：
              </template>
              <span style="padding-left: 15px">{{bidPrice.decimalPlaces}}&nbsp;位</span>
            </el-descriptions-item>
            <el-descriptions-item label-style="text-align: center;height:35px;" span="1.5">
              <template slot="label">
                小数舍弃规则：
              </template>
              <span style="padding-left: 15px">{{bidPrice.decimalRule}}</span>
            </el-descriptions-item>
            <el-descriptions-item label-style="text-align: center;height:35px;" span="3">
              <template slot="label">
                竞标方式：
              </template>
              <span style="padding-left: 15px">{{bidPrice.biddingMethod}}</span>
            </el-descriptions-item>
            <el-descriptions-item label-style="text-align: center;height:35px;" span="3">
              <template slot="label">
                延时规则：
              </template>
              <span style="padding-left: 15px">{{bidPrice.extendTimeRule}}</span>
            </el-descriptions-item>
          </el-descriptions>
        </div>
        <div style="padding:0 100px;text-align: center">
          <p style="font-size: 18px;text-align: center;font-weight: bold;margin-bottom: 5px;">距离结束时间：
            <span style="color: red;">{{ days }}天{{ hours }}时{{ minutes }}分{{ seconds }}秒</span>
            <el-button style="margin-left: 20px;" size="mini" type="danger" @click="refreshCountdown">刷新</el-button>
            <el-button style="margin-left: 30px;" size="mini" type="danger" @click="endBingPrice">结束竞价</el-button>
            <el-button style="margin-left: 30px;" size="mini" type="danger" @click="extendBingPrice">延时一次</el-button><span style="color: red;margin-left: 10px;">共延时&nbsp;{{ bidPrice.currentCount }}&nbsp;次</span>
          </p>
          <div class="content">
            <h2 style="margin-top: 10px;"><i class="fas fa-check-circle"></i>{{ notificationText }}</h2>
          </div>
        </div>
      </el-form>
      <div style="padding-top:0px;border-bottom:0px;padding-left:100px;padding-right:100px;text-align: center">
        <span style="color: red;">当供应商竞价时，请勿离开竞价室，以免错过竞价信息。</span>
      </div>
      <el-form style="width: 1200px;margin: 5px auto 0;">
        <div style="padding:0 100px;text-align: center">
          <span style="text-align: center;font-size: 18px;font-weight: bold;">供应商竞价列表</span>
        </div>
      </el-form>
      <div class="plan-grid-content">
        <el-table v-loading="loading2" :data="biddingPriceList" style="width: 1200px;margin: 5px auto 0;">
          <el-table-column label="供应商排名" align="center" prop="sorted" width="200">
            <template slot-scope="scope">
              {{ scope.row.sorted }}
            </template>
          </el-table-column>
          <el-table-column label="供应商" align="center" prop="hName" width="200">
            <template slot-scope="scope">
              {{ scope.row.hName }}
            </template>
          </el-table-column>
          <el-table-column label="出价次数" align="center" prop="bjCount" width="200">
            <template slot-scope="scope">
              {{ scope.row.bjCount }}
            </template>
          </el-table-column>
          <el-table-column label="最新降价幅度" align="center" prop="bjDecline">
            <template slot-scope="scope">
              {{ scope.row.bjDecline }}&nbsp;%
            </template>
          </el-table-column>
          <el-table-column label="最新竞标金额" :label="currencyCategory" align="center" prop="bjTotal">
            <template slot-scope="scope">
              {{ scope.row.bjTotal }}
            </template>
          </el-table-column>
          <el-table-column label="起始价" :label="startPrice" align="center" prop="startPrice">
            <template slot-scope="scope">
              {{ scope.row.startPrice }}
            </template>
          </el-table-column>
          <el-table-column label="最新竞价时间" align="center" prop="createTime"/>
        </el-table>
      </div>
    </div>
  </div>
</template>

<script>
import {updateUKaiEndTime,updateByUKaiEndTime, findBiddingList, findProcurementPlan, findBiddingRuleBySid} from "@/api/system/tender/bidRules";

export default {
  name: "biddingHall",
  data() {
    return {
      getBiddingCount: 0,
      multiple: 1,
      loading: false,
      uKaiTime: '',
      uKaiEndTime: '',
      days: 0,
      hours: 0,
      minutes: 0,
      seconds: 0,
      isEnd: true,
      countdownInterval: null,
      message: '',
      notificationText: '',
      initialTime: 0,
      currencyCategory: '最新竞标金额(RMB)',
      startPrice: '起始价(RMB)',
      bidForm: {
        uid: null,
        sid: null,
        hid: null,
        uKaiEndTime: null,
      },
      bidPrice: {
        sCode: '',
        currentCount: 0,
      },
      bidPriceInfo: {
        sorted: 0,
        cumulativeDecline: 0.0,
        finalAmount:0.0,
        bidMultiple: null,
        bidPriceTips: '',
        submitText: '点击出价',
      },
      textColor: '#e6a23c',
      tenderQuotation: {
        uid: null,
        sid: null,
        hid: null,
        sCode: null,
        aid: null,
        aaCode: null,
        bjDecline: null,
        bjTotal: null,
      },
      loading2: false,
      biddingPriceList: [],
    };
  },
  created() {
    this.bidForm.sid =this.$route.query.sid;
    this.bidForm.uid = this.$route.query.uid;
    this.tenderQuotation.uid = this.$route.query.uid;
    this.tenderQuotation.sid =this.$route.query.sid;
    this.tenderQuotation.aid =this.$route.query.xyId;
    let type =this.$route.query.type;
    this.getInfo(this.bidForm.sid);
  },
  methods: {
    reset() {
      this.bidForm = {
      }
    },
    // 取消按钮
    cancel() {
      this.reset();
    },
    getInfo(sid) {
      this.loading = true;
      this.loading2 = true;
      findBiddingRuleBySid(sid).then(response=>{
        this.loading = false;
        if(response && response.data){
          this.bidPrice = response.data;
          this.uKaiTime = this.bidPrice.uKaiTime;
          this.uKaiEndTime = this.bidPrice.uKaiEndTime;
          const otherUKaiTime = this.bidPrice.uKaiTime;
          this.tenderQuotation.sCode = this.bidPrice.sCode;
          this.currencyCategory = '最新竞标金额(' + this.bidPrice.currencyCategory + ')';
          this.startPrice = '起始价(' + this.bidPrice.currencyCategory + ')';
          let max = this.bidPrice.maxDecline;
          let min = this.bidPrice.minDecline;
          this.multiple = this.calculateDecimalRatio(max,min);
          const now = new Date().getTime();
          const otherDate = new Date(otherUKaiTime).getTime();
          if(now > otherDate){
            this.startCountdown(this.uKaiEndTime);
          }else{
            this.showNotification('未到竞标时间');
          }
        }
      });
      this.findProcurementPlanInfo(this.tenderQuotation.aid);

      findBiddingList(sid).then(response=>{
        this.loading2 = false;
        if(response && response.data){
          this.biddingPriceList = response.data
        }
      });
    },
    findProcurementPlanInfo(aid){
      findProcurementPlan(aid).then(response=>{
        if(response && response.data){
          this.tenderQuotation.aaCode = response.data.aaCode;
        }
      });
    },
    findTenderQuotationList(sid){
      findBiddingList(sid).then(response=>{
        if(response.data){
          this.biddingPriceList = response.data;
        }
      });
    },
    //结束竞价
    endBingPrice(){
      const endTime = new Date(this.initialTime);
      const now = new Date();
      const difference = endTime - now;
      if (difference <= 0){
        this.$modal.alertWarning("竞价已结束！");
        return;
      }
      const sid = this.tenderQuotation.sid;
      this.$modal.confirm('是否确认结束标号为"' + this.bidPrice.sCode + '"的竞价？').then(function () {
        return updateUKaiEndTime(sid);
      }).then(() => {
        //重新获取信息
        findBiddingRuleBySid(this.tenderQuotation.sid).then(response=>{
          if(response && response.data){
            this.bidPrice = response.data;
            this.uKaiTime = this.bidPrice.uKaiTime;
            this.uKaiEndTime = this.bidPrice.uKaiEndTime;
            this.tenderQuotation.sCode = this.bidPrice.sCode;
            this.refreshCountdown();
          }
        });
        this.$modal.msgSuccess("结束竞价成功");
        //this.$modal.alertWarning("结束竞价成功！");
      }).catch((error) => {
        if(error.toString().includes('非管理员无权限操作')){
          this.$modal.msgWarning("非管理员无权限操作");
        }else if(!error.toString().includes('cancel')){
          this.$modal.msgWarning("结束竞价失败，请重试");
        }
      });
    },
    autoEndBingPrice(){
      const endTime = new Date(this.initialTime);
      const now = new Date();
      const difference = endTime - now;
      if (difference <= 0){
        this.$modal.alertWarning("竞价已结束！");
        return;
      }
      const sid = this.tenderQuotation.sid;
      updateUKaiEndTime(sid).then(response=>{
        if(response && response.code === 200){
          //重新获取信息
          findBiddingRuleBySid(this.tenderQuotation.sid).then(res=>{
            if(res && res.code === 200){
              this.bidPrice = res.data;
              this.uKaiTime = this.bidPrice.uKaiTime;
              this.uKaiEndTime = this.bidPrice.uKaiEndTime;
              this.tenderQuotation.sCode = this.bidPrice.sCode;
              this.refreshCountdown();
            }
          });
          this.$modal.msgSuccess("结束竞价成功");
        }
      }).catch((error) => {
        if(error.toString().includes('非管理员无权限操作')){
          //do nothing
        }else if(!error.toString().includes('cancel')){
          this.$modal.msgWarning("结束竞价失败，请重试");
        }
      });
    },
    //延时一次竞价
    extendBingPrice(){
      const endTime = new Date(this.initialTime);
      const now = new Date();
      const difference = endTime - now;
      if (difference <= 0){
        this.$modal.alertWarning("竞价已结束！");
        return;
      }
      const extendTime = this.bidPrice.extendTime;
      const tempBidForm = {};
      tempBidForm.sid = this.tenderQuotation.sid;
      this.$modal.confirm('是否确认延时竞价一次，往后延时"' + extendTime + '"分钟？').then(function () {
        return updateByUKaiEndTime(tempBidForm);
      }).then((result) => {
        // 这里可以获取到 updateByUKaiEndTime 返回的值
        // 可以根据 result 的值进行不同的处理
        console.log('返回的结果:', result);
        //重新获取信息
        findBiddingRuleBySid(this.tenderQuotation.sid).then(response=>{
          if(response && response.data){
            this.bidPrice = response.data;
            this.uKaiTime = this.bidPrice.uKaiTime;
            this.uKaiEndTime = this.bidPrice.uKaiEndTime;
            this.tenderQuotation.sCode = this.bidPrice.sCode;
            this.refreshCountdown();
          }
        });
        this.$modal.msgSuccess("延时成功");
      }).catch((error) => {
        if(error.toString().includes('延时失败，超过设定的延时次数，即将结束竞价')){
          this.autoEndBingPrice();//结束竞价
        }else if(error.toString().includes('非管理员无权限操作')){
          this.$modal.msgWarning("非管理员无权限操作");
        }else if(!error.toString().includes('cancel')){
          this.$modal.msgWarning("延时失败，请重试，或结束竞价");
        }
      });
    },
    //自动延时一次竞价
    extendBingPriceAutomatic(){
      const endTime = new Date(this.initialTime);
      const now = new Date();
      const difference = endTime - now;
      if (difference <= 0){
        this.$modal.alertWarning("竞价已结束！");
        this.showNotification('竞价已结束无法进入自动延时！');
        return;
      }
      const extendTime = this.bidPrice.extendTime;
      const tempBidForm = {};
      tempBidForm.sid = this.tenderQuotation.sid;
      updateByUKaiEndTime(tempBidForm).then(response=>{
        if(response.code === 200){
          //重新获取信息
          findBiddingRuleBySid(this.tenderQuotation.sid).then(response=>{
            if(response && response.data){
              this.bidPrice = response.data;
              this.uKaiTime = this.bidPrice.uKaiTime;
              this.uKaiEndTime = this.bidPrice.uKaiEndTime;
              this.tenderQuotation.sCode = this.bidPrice.sCode;
              this.refreshCountdown();
            }
          });
        }
      }).catch((error) => {
        if(error.toString().includes('延时失败，超过设定的延时次数，即将结束竞价')){
          this.autoEndBingPrice();//结束竞价
        }else if(error.toString().includes('非管理员无权限操作')){
          //do nothing
        }else if(!error.toString().includes('cancel')){
          this.$modal.msgWarning("延时失败，请重试，或结束竞价");
        }
      });
    },
    //计算两数之间的倍数
    calculateDecimalRatio(num1, num2) {
      // 验证输入是否为有效数字
      if (typeof num1 !== 'number' || typeof num2 !== 'number' || isNaN(num1) || isNaN(num2)) {
        throw new Error('两个参数都必须是有效数字');
      }
      // 处理除数为零的情况
      if (num2 === 0) {
        if (num1 === 0) {
          return NaN; // 0/0 是不确定的
        }
        return num1 > 0 ? Infinity : -Infinity; // 返回正无穷或负无穷
      }
      // 计算倍数
      const result = num1 / num2;
      // 处理浮点数精度问题，保留最多10位小数
      return parseFloat(result.toFixed(10));
    },
    // 开始倒计时
    startCountdown(endTimeParam = null) {
      // 清除现有的倒计时
      if (this.countdownInterval) {
        clearInterval(this.countdownInterval);
      }
      // 使用参数或输入框的值
      const targetTime = endTimeParam;
      if (!targetTime) {
        this.showNotification('请先设置结束时间！');
        return;
      }
      this.initialTime = new Date(targetTime).getTime();
      this.updateCountdown();
      // 每秒更新一次倒计时
      this.countdownInterval = setInterval(() => {
        this.updateCountdown();
      }, 1000);
      this.showNotification('正在倒计时');
    },
    // 刷新倒计时（接收新参数）
    refreshCountdown() {
      //重新获取信息
      findBiddingRuleBySid(this.tenderQuotation.sid).then(response=>{
        if(response && response.data){
          this.bidPrice = response.data;
          this.uKaiTime = this.bidPrice.uKaiTime;
          this.uKaiEndTime = this.bidPrice.uKaiEndTime;
          this.tenderQuotation.sCode = this.bidPrice.sCode;

          // 在实际应用中，这里可以接收新的结束时间参数
          const now = new Date().getTime();
          const otherDate = new Date(this.uKaiTime).getTime();
          if(now > otherDate){
            this.startCountdown(this.uKaiEndTime);
          }else{
            this.showNotification('未到竞标时间');
          }
        }
      });
      //已刷新倒计时时间
    },
    // 更新倒计时显示
    updateCountdown() {
      const endTime = new Date(this.initialTime);
      const now = new Date();
      const difference = endTime - now;
      if (difference <= 0) {
        this.days = 0;
        this.hours = 0;
        this.minutes = 0;
        this.seconds = 0;
        this.progress = 0;
        this.message = '时间已到！';
        this.isEnd = true;
        this.showNotification('竞价结束！');
        clearInterval(this.countdownInterval);

        //最后再刷新竞价列表
        this.findTenderQuotationList(this.bidForm.sid);
        this.handlerNoticeBiddingEnd();//通知竞价结束
        return;
      }
      if((endTime.getTime() - now.getTime() < 8000 && endTime.getTime() - now.getTime() > 7000)){
        this.extendBingPriceAutomatic();
      }else{
        if((endTime.getTime() - now.getTime() < 100000 && endTime.getTime() - now.getTime() > 99000)
          || (endTime.getTime() - now.getTime() < 95000 && endTime.getTime() - now.getTime() > 94000)
          || (endTime.getTime() - now.getTime() < 90000 && endTime.getTime() - now.getTime() > 89000)
          || (endTime.getTime() - now.getTime() < 85000 && endTime.getTime() - now.getTime() > 84000)
          || (endTime.getTime() - now.getTime() < 80000 && endTime.getTime() - now.getTime() > 79000)
          || (endTime.getTime() - now.getTime() < 75000 && endTime.getTime() - now.getTime() > 74000)
          || (endTime.getTime() - now.getTime() < 70000 && endTime.getTime() - now.getTime() > 69000)
          || (endTime.getTime() - now.getTime() < 65000 && endTime.getTime() - now.getTime() > 64000)
          || (endTime.getTime() - now.getTime() < 60000 && endTime.getTime() - now.getTime() > 59000)
          || (endTime.getTime() - now.getTime() < 55000 && endTime.getTime() - now.getTime() > 54000)){
          this.$modal.msgSuccess("竞价结束后默认进入延时，如需结束，请及时结束竞价！");
          this.showNotification('竞价结束后默认进入延时，如需结束，请及时“结束竞价”！竞价结束前10秒内不要离开界面，否则不能自动延时！');
        }
        if((endTime.getTime() - now.getTime() < 50000 && endTime.getTime() - now.getTime() > 49000)
          || (endTime.getTime() - now.getTime() < 40000 && endTime.getTime() - now.getTime() > 39000)
          || (endTime.getTime() - now.getTime() < 30000 && endTime.getTime() - now.getTime() > 29000)
          || (endTime.getTime() - now.getTime() < 20000 && endTime.getTime() - now.getTime() > 19000)){
          this.$modal.msgWarning("竞价即将结束，如需结束，请及时结束竞价！");
          this.showNotification('即将结束并自动延时，如需结束，请及时“结束竞价”！竞价结束前10秒内不要离开界面，否则不能自动延时！');
        }
        if((endTime.getTime() - now.getTime() < 19000 && endTime.getTime() - now.getTime() > 18000)
          || (endTime.getTime() - now.getTime() < 16000 && endTime.getTime() - now.getTime() > 15000)
          || (endTime.getTime() - now.getTime() < 13000 && endTime.getTime() - now.getTime() > 12000)
          || (endTime.getTime() - now.getTime() < 10000 && endTime.getTime() - now.getTime() > 9000)
          || (endTime.getTime() - now.getTime() < 7000 && endTime.getTime() - now.getTime() > 6000)){
          this.$modal.msgError("即将结束，请及时操作！");
          this.showNotification('即将结束，请及时操作！');
        }
      }

      this.isEnd = false;
      // 计算天、时、分、秒
      const totalSeconds = Math.floor(difference / 1000);
      this.days = Math.floor(totalSeconds / (3600 * 24));
      this.hours = Math.floor((totalSeconds % (3600 * 24)) / 3600);
      this.minutes = Math.floor((totalSeconds % 3600) / 60);
      this.seconds = Math.floor(totalSeconds % 60);

      this.getBiddingCount ++;
      //刷新竞价列表
      if(this.getBiddingCount % 5 === 0){
        this.findTenderQuotationList(this.bidForm.sid);
      }
    },
    // 显示通知
    showNotification(text) {
      this.notificationText = text;
    },
    handlerNoticeBiddingEnd() {
      // 通知刷新候选人公示
      const method2 = this.$store.state.bidRulesShared.sharedMethods.noticeChangeStep
      if (method2) method2();
    },
    //格式化时间
    parseTime(time, pattern) {
      if (arguments.length === 0 || !time) {
        return null
      }
      const format = pattern || '{y}-{m}-{d} {h}:{i}:{s}'
      let date
      if (typeof time === 'object') {
        date = time
      } else {
        if ((typeof time === 'string') && (/^[0-9]+$/.test(time))) {
          time = parseInt(time)
        } else if (typeof time === 'string') {
          time = time.replace(new RegExp(/-/gm), '/').replace('T', ' ').replace(new RegExp(/\.[\d]{3}/gm), '');
        }
        if ((typeof time === 'number') && (time.toString().length === 10)) {
          time = time * 1000
        }
        date = new Date(time)
      }
      const formatObj = {
        y: date.getFullYear(),
        m: date.getMonth() + 1,
        d: date.getDate(),
        h: date.getHours(),
        i: date.getMinutes(),
        s: date.getSeconds(),
        a: date.getDay()
      }
      const time_str = format.replace(/{(y|m|d|h|i|s|a)+}/g, (result, key) => {
        let value = formatObj[key]
        // Note: getDay() returns 0 on Sunday
        if (key === 'a') { return ['日', '一', '二', '三', '四', '五', '六'][value] }
        if (result.length > 0 && value < 10) {
          value = '0' + value
        }
        return value || 0
      })
      return time_str
    },
  },
  mounted() {
  },
  beforeDestroy() {
    // 组件销毁前清除定时器
    if (this.countdownInterval) {
      clearInterval(this.countdownInterval);
    }
  }
};
</script>
<style>
.box {
  margin: 10px 0 15px 0px;
  color: #0065B5;
  font-size: 16px;
  font-weight: bold;
}
.form-input{
  width: 500px;
  display: inline-block;
}

.bidding-hall-margin-top .el-descriptions--medium.is-bordered .el-descriptions-item__cell {
  padding: 0 0px;
}

</style>
